<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:27
 */


namespace app\member\controller;

use app\common\controller\Common;
use my\RedisPackage as redis;
use think\Request;
use think\Response;
use think\exception\HttpResponseException;
use think\Db;

/**
 * 前台公共控制器
 * @package app\index\controller
 */
class Base extends Common
{
    /**
     *
     * @var Request Request 实例
     */
    protected $request;


    /**
     *  会员ID
    **/
    protected $user_id = 0;

    /**
     *  会员详情
    **/
    protected $user_info = 0;

    /**
     *  门店ID
    **/
    protected $store_id = 0;

    /**
     *  房间ID
    **/
    protected $room_id = 0;

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';


    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
        // 控制器初始化
        $this->_initialize();
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: " . $this->request->server('HTTP_ORIGIN'));
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');
        }
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
            }
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            }
        }
        //移除HTML标签
        //$this->request->filter('trim,strip_tags,htmlspecialchars');

        $token    = $this->request->param('token');     //会员登陆标识

        $store_id = $this->request->param('store_id');  //门店ID

        $room_id  = $this->request->param('room_id');   //房间ID
        if (empty($store_id))
        {
            $this->result('门店不存在','',204);
        }

        $this->store_id = $store_id;

        if (!empty($room_id))
        {
            $this->room_id  = $room_id;
        }


        // 系统开关
        if (!config('web_site_status')) {
            $this->result('站点已经关闭，请稍后访问~');
        }

        // 检测是否需要验证登录
        if (!$this->match($this->noNeedLogin)) {

            //检测是否登录
            if (!$token) {
                $this->result('请先登录', null, 203);
            } else {
                $user = Db::name('qt_user_viper')->where('login_token', $token)->find();
                if (empty($user))
                {
                    $this->result('请先登录', '', 203);
                }
                $this->user_info = $user;
                $this->user_id = $user['id'];
            }
        }
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型，支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => $this->request->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = 200;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }


    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    protected function match($arr = [])
    {
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($this->request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }


    /**
     *  通过 token 获取用户ID
     * @param  string  token
     * @return boolean
     * @throws
     **/
    public function getUserId()
    {
        $user_id    = 0;
        $token      = $this->request->param('token','');
        if(!empty($token))
        {
            $user    = Db::name('qt_user_viper')->where("login_token",$token)->find();
            if($user)
            {
                $user_id = $user['id'];  //赋值用户ID
            }
        }

        return $user_id;
    }


}

